from pydantic import BaseModel
from abc import ABC, abstractmethod
from typing import List, Any, Optional
import scrapy
from io import BytesIO
import os
from PIL import Image
from utils.captcha_recognizer import CaptchaRecognizer
from utils.js_executor import JavaScriptExecutor
from setting import ProjectSetting
from model import Account


class BaseSpider(scrapy.Spider):
    name: str
    account: Optional[Account]
    js_executor = JavaScriptExecutor
    data_dir: str
    max_retry_count = 10

    def __init__(self):
        super().__init__()
        self.prepare()
        self.custom_settings = {
            "LOG_ENABLED": True,
            "LOG_LEVEL": 'INFO',
            "LOG_FILE": os.path.join(ProjectSetting.LOG_DIR, "{}-spider.log".format(self.name)),
        }

    def start_requests(self):
        ...

    def prepare(self):
        data_dir = os.path.join(ProjectSetting.DATA_DIR, self.name)
        if not os.path.exists(data_dir):
            os.makedirs(data_dir)
        self.data_dir = data_dir

    def parse(self, response):
        ...

    def after_login(self, response):
        ...

    def save_captcha_image(self, response, image_path):
        image_data = BytesIO(response.body)
        img = Image.open(image_data)
        img.save(image_path)

    def recognize_image_code(self, image_path, verify_type):
        captcha_code = ""
        captcha_recognizer = CaptchaRecognizer()
        captcha_code = captcha_recognizer.common_verify(image_path=image_path, verify_type=verify_type)
        return captcha_code

    def login_and_fetch_data(self, response):
        ...